package com.hzit.auth.filter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.hzit.auth.entity.LoginUser;
import com.hzit.common.constants.CommonConstants;
import com.hzit.common.util.JwtUtil;
import com.hzit.common.util.R;
import com.hzit.common.util.ResponseUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

import static com.hzit.common.constants.CommonConstants.AUTH_LOGIN_REDIS_PREFIX;

/**
 * 类名：
 * 作者：WF
 * 功能：授权过滤器(判断在控制器中使用的@PreAuthorize("hasAuthority('user:userlist')")权限串是否在登录成功的用户的权限列表中)
 */
@Component
public class HzitAuthenticationFilter extends OncePerRequestFilter {
	@Autowired
	private StringRedisTemplate redisTemplate;
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
		//1. 得到请求头
		String header = request.getHeader(CommonConstants.AUTH_HEADER_PREFIX);
		if(StrUtil.isBlank(header)){
			filterChain.doFilter(request,response);
			return;
		}
		//2. 处理请求头
		String token = header.replaceAll(CommonConstants.AUTH_HEADER_BEARER_PREFIX, "");
		//3. 如要存在就解析它
		if(StrUtil.isNotBlank(token)){
			Claims claims = JwtUtil.parseToken(token);
			String uuidToken = (String) claims.get("token");
			if(StrUtil.isBlank(uuidToken)){
				throw new RuntimeException("解析token异常！");
			}
			//4. 得到redis的key
			String key = getKey(uuidToken);
			String s = redisTemplate.opsForValue().get(key);
			//5. 转换为登录对象
			LoginUser user = JSON.parseObject(s,LoginUser.class);
			if(!Objects.isNull(user)){
				//6. 构造一个UsernamepasswordToken对象
				UsernamePasswordAuthenticationToken upat = new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword(),user.getAuthorities());
				SecurityContextHolder.getContext().setAuthentication(upat);
			}else{
				ResponseUtil.out(response, R.fail("请先登录！"));
			}
		}
		//7. 放行过滤器
		filterChain.doFilter(request,response);
	}
	// 获取到redis的key
	private String getKey(String uuidToken) {
		return AUTH_LOGIN_REDIS_PREFIX + uuidToken;
	}
}
